import React, { PureComponent, Fragment } from 'react';

import { connect } from 'dva';

import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Badge, Divider, Steps, Radio, Popover, Popconfirm } from 'antd';

import StandardTable from '@/components/StandardTable';
import StandardTableForm from '@/components/StandardTable/StandardTableForm';
import StandardTableHandle from '@/components/StandardTable/StandardTableHandle';

import { bannersCenter as columns } from '@/commons/columns';
import { bannersManage as map } from '@/commons/map';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
  .map(key => obj[key])
  .join(',');

/* eslint react/no-multi-comp:0 */
@connect(({ bannerSelect, loading }) => ({
  bannerSelect,
  loading: loading.models.bannerSelect,
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };

  columns = columns;

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'bannerSelect/fetch',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      from: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'bannerSelect/fetch',
      payload: { ...params },
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();

    this.setState({
      formValues: {},
    });

    dispatch({
      type: 'bannerSelect/fetch',
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'add':
        dispatch({
          type: 'bannerSelect/update',
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (!errno && data) {
              dispatch({
                type: 'bannerSelect/fetch',
              });

              dispatch({
                type: 'bannerManage/fetch',
              });

              this.setState({
                selectedRows: []
              });

              message.success(`选择广告成功 ${data} 条`);
            } else {
              message.error('选择广告失败！');
            }
          },
        });
        break;
      default:
        message.error('不清楚你在做什么')
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState(state => ({
      ...state,
      selectedRows: rows,
    }));
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        endAt: fieldsValue.endAt && fieldsValue.endAt.format('YYYY-MM-DD hh:mm'),
        createdAt: fieldsValue.createdAt && fieldsValue.createdAt.format('YYYY-MM-DD hh:mm'),
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.format('YYYY-MM-DD hh:mm'),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'bannerSelect/fetch',
        payload: { ...values, },
      });
    });
  };

  render() {
    const {
      bannerSelect: { data, type },
      loading,
      form,
    } = this.props;
    const { expandForm, selectedRows } = this.state;

    return (
      <Fragment>
        <StandardTableForm
          expandForm={expandForm}
          data={map}
          form={form}
          onSubmit={this.handleSearch}
          onReset={this.handleFormReset}
          onToggle={this.toggleForm}
        />
        {
          (selectedRows.length > 0)
          ?
          <StandardTableHandle
            selectedRows={selectedRows}
            menuItems={{'add': <Fragment><Button type="primary" icon="select">选择</Button></Fragment>}}
            onMenuClick={this.handleMenuClick}
          />
          :
          null
        }
        <StandardTable
          selectedRows={selectedRows}
          loading={loading}
          data={data}
          bordered={true}
          size="small"
          columns={this.columns}
          expandedRowRender={record => <p style={{ marginBottom: 0 }}>备注：{record.remark}</p>}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </Fragment>
    );
  }
}

export default TableList;